package com.chen.lifepic.downloader;

import java.util.Vector;

public class AsyncTaskQueue {
	Vector<BaseTask> _tasks = null;

	boolean _isThreadRun = false;

	Thread _downloadThread = null;

	public AsyncTaskQueue() {
		_tasks = new Vector<BaseTask>();
	}

	public void destroy() {
		stopDownloadThread();

		if (null != _tasks) {
			_tasks.removeAllElements();
			_tasks = null;
		}
	}

	public void removeAllTasks() {
		if (null != _tasks) {
			_tasks.removeAllElements();
		}

		stopDownloadThread();
	}

	public void putToQueue(BaseTask task) {
		_tasks.add(task);
		runTaskThreadIfNeeded();
	}

	void runTaskThreadIfNeeded() {
		if (_isThreadRun)
			return;

		stopDownloadThread();

		_downloadThread = new Thread(downloadRunnable);
		_downloadThread.start();
	}

	void stopDownloadThread() {
		try {
			if (null != _downloadThread) {
				_downloadThread.interrupt();
				_downloadThread = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	Runnable downloadRunnable = new Runnable() {
		@Override
		public void run() {
			_isThreadRun = true;
			while (true) {
				try {
					if (null == _tasks || 0 == _tasks.size()) {
						_isThreadRun = false;
						return;
					}

					BaseTask task = _tasks.get(0);
					if (null == task) {
						Thread.sleep(100);
						continue;
					}

					task.start();
					_tasks.remove(task);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};
}
